package cn.school.student.service.impl;


import cn.school.student.dao.ExamPublishStudentDao;
import cn.school.student.dao.TExamPerformanceDao;
import cn.school.student.entity.ExamPublishStudent;
import cn.school.student.entity.TExamPerformance;
import cn.school.student.entity.vo.UnitVo;
import cn.school.student.service.TExamPerformanceService;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.base.Joiner;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.PageRequest;
import org.springframework.util.StringUtils;


import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 考試成績表(TExamPerformance)表服务实现类
 *
 * @author makejava
 * @since 2023-02-16 17:41:51
 */
@Service("tExamPerformanceService")
public class TExamPerformanceServiceImpl implements TExamPerformanceService {
    @Resource
    private TExamPerformanceDao tExamPerformanceDao;

    @Resource
    private ExamPublishStudentDao examPublishStudentDao;

    /**
     * 通过ID查询单条数据
     *
     * @param studentId 主键
     * @return 实例对象
     */
    @Override
    public TExamPerformance queryById(Long studentId) {
        return this.tExamPerformanceDao.queryById(studentId);
    }

    /**
     * 分页查询
     *
     * @param tExamPerformance 筛选条件
     * @param pageRequest      分页对象
     * @return 查询结果
     */
    @Override
    public IPage<TExamPerformance> queryByPage(TExamPerformance tExamPerformance, PageRequest pageRequest) {
        Integer count = (int) tExamPerformanceDao.count(tExamPerformance);
        List<TExamPerformance> examInfoList = tExamPerformanceDao.queryAllByLimit(tExamPerformance, pageRequest);
        IPage<TExamPerformance> page = new Page<>();
        page.setTotal(count);
        page.setRecords(examInfoList);
        return page;
    }

    /**
     * 新增数据
     *
     * @param tExamPerformance 实例对象
     * @return 实例对象
     */
    @Override
    public Integer insert(TExamPerformance tExamPerformance) {
        int insert = this.tExamPerformanceDao.insert(tExamPerformance);
        return insert;
    }

    /**
     * 修改数据
     *
     * @param tExamPerformance 实例对象
     * @return 实例对象
     */
    @Override
    public Integer update(TExamPerformance tExamPerformance) {
        int update = this.tExamPerformanceDao.update(tExamPerformance);
        return update;
    }

    /**
     * 通过主键删除数据
     *
     * @param studentId 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long studentId) {
        return this.tExamPerformanceDao.deleteById(studentId) > 0;
    }

    @Override
    public int submitTestpaper(List<TExamPerformance> tExamPerformances) {
        //去除没有填写答案的和问答题
//        List<TExamPerformance> list = tExamPerformances.stream().filter((tExamPerformance)
//                        -> tExamPerformance.getStuResult() != null && !tExamPerformance.getStuResult().equals("")
//                        &&  !tExamPerformance.getQuestionsType().equals("5")).collect(Collectors.toList());
        LambdaQueryWrapper<ExamPublishStudent> studentWrapper = new LambdaQueryWrapper<>();
        BigDecimal countScore = BigDecimal.ZERO;
        if(tExamPerformances==null || tExamPerformances.size()==0){
            return -1;
        }
        //是否需要手动批改
        boolean isCorrect = false;
        for (TExamPerformance tExamPerformance : tExamPerformances) {
            boolean pCorrect = false;
            //填空题
            if (tExamPerformance.getQuestionsType().equals("4")){
                setResultList(tExamPerformance);
//                isCorrect = true;
//                pCorrect = true;
            }
            //多选题
            if (tExamPerformance.getQuestionsType().equals("2")){
                List<String> txtList = getUnitList(tExamPerformance);
                String unitResult = Joiner.on(",").join(txtList);
                setResult(tExamPerformance, unitResult);
            }
            // 选择题 or 判断题
            if (tExamPerformance.getQuestionsType().equals("1") || tExamPerformance.getQuestionsType().equals("3")){
                String unit = tExamPerformance.getUnit();
                setResult(tExamPerformance, unit);
            }
            // 问答题
            if (tExamPerformance.getQuestionsType().equals("5")){
//                String unit = tExamPerformance.getUnit();
//                setResult(tExamPerformance, unit);
                isCorrect = true;
                pCorrect = true;
            }

            LambdaQueryWrapper<TExamPerformance> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(TExamPerformance::getId,tExamPerformance.getId());

            TExamPerformance exentity = new TExamPerformance();
            exentity.setGradesScores(tExamPerformance.getGradesScores());
            exentity.setIsRight(tExamPerformance.getIsRight());
            exentity.setStuResult(tExamPerformance.getStuResult());
            exentity.setId(tExamPerformance.getId());
            //问答题和填空题要手工批改
            exentity.setCorrectStatus(pCorrect?"0":"2");
            this.tExamPerformanceDao.updateById(exentity);
            //计算考试总分
            countScore = countScore.add(new BigDecimal(exentity.getGradesScores()));
            //更新学生考试更新条件
            studentWrapper.eq(ExamPublishStudent::getPublishId,tExamPerformance.getPublishId());
            studentWrapper.eq(ExamPublishStudent::getStudentId,tExamPerformance.getStudentId());
        }
        ExamPublishStudent epsInfo = new ExamPublishStudent();
        epsInfo.setIsSubmit(1L);
        epsInfo.setSubmitTime(new Date());
        epsInfo.setExamScore(countScore);
        //批改状态 0：未批改 1：已批改 2：自动批改
        epsInfo.setCorrectStatus(isCorrect?"0":"2");

        return   examPublishStudentDao.update(epsInfo,studentWrapper);

    }

    @NotNull
    private List<String> getUnitList(TExamPerformance tExamPerformance) {
        List<UnitVo> voList = JSON.parseArray(tExamPerformance.getUnit(), UnitVo.class);
        List<String> txtList = new ArrayList<>();
        for (UnitVo vo : voList) {
            if (vo.getIsRight()) {
                txtList.add(vo.getOptIdx());
            } else {
                continue;
            }
        }
        return txtList;
    }

    private void setResult(TExamPerformance tExamPerformance, String unit) {
        if (!StringUtils.isEmpty(tExamPerformance.getStuResult())&&tExamPerformance.getStuResult().equals(unit)) {
            tExamPerformance.setIsRight("1");
            tExamPerformance.setGradesScores(tExamPerformance.getScoresScore());
        }else{
            tExamPerformance.setIsRight("0");
            tExamPerformance.setGradesScores("0");
        }
    }

    private void setResultList(TExamPerformance tExamPerformance) {

        List<UnitVo> list = JSON.parseArray(tExamPerformance.getUnit(),UnitVo.class);
        if(StringUtils.isEmpty(tExamPerformance.getStuResult())
                || tExamPerformance.getStuResult().split(";").length != list.size()){
            tExamPerformance.setIsRight("0");
            tExamPerformance.setGradesScores("0");
            return;
        }
        String [] str = tExamPerformance.getStuResult().split(";");
        int num=0;
        for(int i=0;i<list.size();i++){
            if(list.get(i).getOptTxt().equals(str[i])){
                num++;
            }
        }
        if(num==list.size()){
            tExamPerformance.setIsRight("1");
            tExamPerformance.setGradesScores(tExamPerformance.getScoresScore());
        }else{
            tExamPerformance.setIsRight("0");
            tExamPerformance.setGradesScores("0");
        }

    }
}
